﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;
using PicShare.Data;
using PicShare.Server.Models;

namespace PicShare.Server.Repositories
{
    public class UsersRepository : IRepository<User>
    {
        public readonly MongoDbContext<User> DbContext;
        public UsersRepository(MongoDbContext<User> dbContext)
        {
            DbContext = dbContext;
        }

        public void Add(User item)
        {
            DbContext.MongoCollection.Insert(item);
        }

        public void Remove(User item)
        {
            throw new NotImplementedException();
        }

        public void Clear()
        {
            while (true)
            {
                var user = DbContext.MongoCollection.AsQueryable().FirstOrDefault();

                if (user == null)
                {
                    break;
                }

                var query = Query<User>.EQ(e => e.Id, user.Id);
                DbContext.MongoCollection.Remove(query);
            }
        }

        public IQueryable<User> GetAll()
        {
            return DbContext.MongoCollection.AsQueryable();
        }

        public User Find(Func<User, bool> predicate)
        {
            return DbContext.MongoCollection.AsQueryable().FirstOrDefault(predicate);
        }

        public User Update(User user)
        {
            DbContext.MongoCollection.Save(user);
            return user;
        }
    }
}